import time
import uuid

from fastapi import FastAPI,Request,HTTPException,status
from starlette.middleware.base import BaseHTTPMiddleware
from loguru import logger
from starlette.responses import JSONResponse

from common.ResponseModel import ResponseModel


class LoggingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        request_id = str(uuid.uuid4())

        with logger.contextualize(request_id=request_id):
            logger.info("Request started")
            try:
                response = await call_next(request)
            except Exception as ex:
                logger.error(f"Request failed: {ex}")
                return JSONResponse( content= ResponseModel.error(code=status.HTTP_500_INTERNAL_SERVER_ERROR,message="internal server"),status_code=500)
            finally:
                logger.info("Request ended")
        return response